package cc.rengu.igas.bsps.common.util;

import cc.rengu.igas.bsps.common.dao.BspsMchntBaseInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBaseInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntBaseInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.enums.BindStatusEnum;
import cc.rengu.igas.bsps.common.enums.MchntStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.base.BaseResponse;
import cc.rengu.igas.momp.facade.base.Header;
import cc.rengu.igas.momp.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * @author Xuegui Cao
 * @date 2020/7/2
 * @description HTTP请求调用[MOMP]Dubbo服务时工具类
 */
public class ChangeDubboUtil {

    private static final String ONE_COMMON_CONSTANT = "1";

    /**
     * 获取商户签约机构,同时进行商户绑定关系校验
     */
    public static String getSignInstId() throws Exception {
        RgLogger rglog = RgLog.getLogger(ChangeDubboUtil.class.getName());
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        String userId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.USER_ID);
        String mchntNo = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO);
        if (StringUtil.isEmptyOrNull(mchntNo)) {
            mchntNo = xmlTreeUtil.getXmlTreeStringValue("queryOrgId");
            if (StringUtil.isEmptyOrNull(mchntNo)) {
                rglog.debug("未上送商户号,交易拒绝.");
                throw new BizException(OltpRpcdEnum.PARAM_IS_EMPTY_OR_NULL.getRespCode(), OltpRpcdEnum.PARAM_IS_EMPTY_OR_NULL.getRespDesc());
            }
        }

        BspsMchntBindInfoMapper mchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        MchntBindInfo mchntBindInfo = mchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, userId, mchntNo);
        if (null == mchntBindInfo || !BindStatusEnum.BIND.getStatus().equals(mchntBindInfo.getBindStatus())) {
            rglog.error("获取用户<{}>绑定商户<{}>信息失败", userId, mchntNo);
            throw new BizException(RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespDesc());
        }
        BspsMchntBaseInfoMapper mchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo || !MchntStatusEnum.NORMAL.getStatus().equals(mchntBaseInfo.getMchntStatus())) {
            rglog.debug("查询商户<{}>基本信息失败.", mchntNo);
            throw new BizException(RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespDesc());
        }
        return mchntBaseInfo.getSignInstId();
    }

    /**
     * 更改请求Header的ChanlId,TxnNum,TraceNo信息,srcSysId设置为[MOMP]
     *
     * @param header cc.rengu.igas.momp.facade.base.Header对象
     * @param chanID 渠道标志
     * @param txnNum 交易码
     */
    public static Header changeHeader(Header header, String chanID, String txnNum) {
        RgLogger rglog = RgLog.getLogger(ChangeDubboUtil.class.getName());
        //判空
        if (header == null || StringUtil.isEmptyOrNull(chanID) || StringUtil.isEmptyOrNull(txnNum)) return header;

        // header.setSrcSysId(ChannelEnum.MOMP.getChannelType());
        header.setSrcSysId(AppParamConstant.SYS_ID);

        header.setChanlId(chanID);//Task 1 渠道标志赋值
        header.setTxnNum(txnNum);//Task 2 交易码赋值

        //Task 3 流水号赋值
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sSysSeqNum = null;
        try {
            //eg:BSPS0000202007021124010000093502
            sSysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        } catch (Exception e) {
            rglog.error(e.getMessage());
        }
        rglog.debug("前端流水号：{}", header.getTraceNo());
        rglog.debug("更改后的流水号：{}", sSysSeqNum);

        //scheme 1
        // String sSysSeqNum2 = sSysSeqNum.substring(sSysSeqNum.length() - 11);
        // long lSysSeqNum = Long.parseLong(sSysSeqNum2) + 1;
        // String sSysSeqNum3 = sSysSeqNum.substring(0, sSysSeqNum.length() - 11) + lSysSeqNum;
        // header.setTraceNo(sSysSeqNum3);

        //scheme 2
        // String sSysSeqNum2 = sSysSeqNum.substring(sSysSeqNum.length() - 6);
        // int iSysSeqNum3 = Integer.parseInt(sSysSeqNum2) + 1;
        // String sSysSeqNum4 = String.valueOf(iSysSeqNum3);
        // if (sSysSeqNum4.length() < 6) {
        //     sSysSeqNum4 = "0" + sSysSeqNum4;
        // }
        // String sSysSeqNum5 = sSysSeqNum.substring(0, sSysSeqNum.length() - 6) + sSysSeqNum4;
        // header.setTraceNo(sSysSeqNum5);

        //scheme 3
        sSysSeqNum = sSysSeqNum + ONE_COMMON_CONSTANT;
        header.setTraceNo(sSysSeqNum);

        return header;
    }

    /**
     * 修改请求Header,不送chanId时,默认为【BSPS】
     *
     * @param header
     * @param sTxnNum
     * @return
     */
    public static Header changeHeader(Header header, String sTxnNum) {
        String defaultChanId = ChannelEnum.BSPS.getChannelType();
        return changeHeader(header, defaultChanId, sTxnNum);
    }

    /**
     * set【BizResponse】中的值
     *
     * @param bizResponse
     * @param rspSysId
     * @param result
     */
    public static BizResponse setBizResponse(BizResponse bizResponse, String rspSysId, Result result) {
        bizResponse.setResult(result.getResult());
        bizResponse.setRspSysId(rspSysId);
        BaseResponse baseResponse = (BaseResponse) result.getResult();
        bizResponse.setRespCode(baseResponse.getRespCode());
        bizResponse.setRespDesc(baseResponse.getRespDesc());
        return bizResponse;
    }
}
